/*
NAME:
DESCRIPTION: ;
PARAMETER:
    [ 
		{  
			name : 'step_fliter',
			title : 'Step过滤',
			type : 'LineEdit',
			property : {tool_tip : 'unit'},
		},
		{
            name : 'checklist_cfg',
			title : 'checklist配置',
			type : 'TextEdit',
            property : {tool_tip : 'checklist配置'},
            setter:function(obj,value,self){
                obj.setPlainText(value);
            },
            getter:function(obj,self){
                return obj.plainText
            }
		},
		{
			name : 'layer_type',
			title : '工作层',
			type : 'ComboBox',
			property : {
			    size_policy:'Expanding,Fixed',
			    item_list:[
			        {name:'outer',text:'outer'},
			        {name:'inner',text:'inner'},
			        {name:'all',text:'all'}
			    ],
			    tool_tip:'分析模式必须设置，未设定则退出'
			},
			pack : {row:1,column:1},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-28 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 标题 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> 配置 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>JTG_PUB_pos_up_pad_aim start ");
/* question
    ?
*/
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db;
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];
var isGjb = /gjb362b2009|ipca600h3/.test(IKM.get_jobinfo({jobid:JobId, jobinfo:"acceptance_level"}));
try {
	var par = PAR;
	var default_par = {  // par默认参数？
		step_fliter:"unit.+",
		step2:"unit",
		units: "mm",
		auto_save: "no"
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	
	if(_.isEmpty(Job)){throw "参数Job不存在"}
    var job = Job.toLowerCase()
    // 料号验证
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
	if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }
	
	// 脚本开始
	var checklist_cfg = false;
	if(par.checklist_cfg && par.checklist_cfg != "") {
		// checklist_cfg = eval(par.checklist_cfg)
		checklist_cfg = JSON.parse(par.checklist_cfg)
	}
	var layer_config = {
		outer: {layer_type:"signal", side:"top|bottom", context:"board", polarity:"positive"},
		inner: {layer_type:"signal", side:"inner", context:"board", polarity:"positive"},
		all: {layer_type:"signal", context:"board", polarity:"positive"},
		power_ground: {layer_type:"power_ground", side:"inner", context:"board", polarity:"negative"},
	} 
	var layer_cfg
	if(par.layer_type != ""){
		layer_cfg = layer_config[par.layer_type]
	}
	var matrix = GEN.getMatrix({job:job})
	var n_layers = Object.keys(matrix).sort(function(a,b){return matrix[a].row - matrix[b].row})
	.filter(function(key){
		var val = matrix[key]
		var flag = true
		if(!layer_cfg){ return false}
		for(var k in layer_cfg){
			var tmp_reg = new RegExp(layer_cfg[k], "ig")
			if(!tmp_reg.test(val[k])){
				flag = false
			}
		}
		return flag
	})
	if(n_layers.length == 0){throw "can not find layer"}
	var stepList = GEN.getStepList({job:job})
	if(par.step_fliter != ""){
		stepList = stepList.filter(function(v){
			var step_reg = new RegExp(par.step_fliter)
			return step_reg.test(v)})
	}
	if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job: job}).filter(function (v) {
			var step_reg = new RegExp(par.step2)
			return step_reg.test(v)
		})
	}

	// 获取料号info copper_base_thk_outer
	var layer_type = par.layer_type    // outer inner all power_ground
	var jtg_etch_process_mode = getJobInfo("jtg_etch_process_mode") // 酸:mask_hole 碱:plat_grapic 无:non
	var erf = (layer_type == "inner") ? "Inner Padup other" : "Outer Padup other"
	var copper_etching_thk_outer = IKM.get_jobinfo({jobid:JobId, jobinfo:"copper_etching_thk_outer"})


	var ret = IKM.crud('selectArrayMap', {
        table: "pdm_job_stack_layers",
        field: ["layer_name","raw_thk"],
        where: {job_id:JobId}
	}).filter(function(item){return item.layer_name})
    var layerCount = IKM.get_jobinfo({jobid: JobId,jobinfo:"layer_count"}) || GEN.getLayerCount({job:job})
    var info = {};
    
    ret.map(function(row) {
        var layer = getRow(row.layer_name,layerCount) 
		var raw_thk = row.raw_thk
		info[layer] = raw_thk
	})

	// 阴阳铜
	var cores = IKM.crud('selectArrayMap', {
        table: "pdm_job_stack_layers",
        field: ["layer_num"],
        where: {job_id:JobId, layer_type:"Core"}
	})
	cores.forEach(function(num){
		var num1 = Math.floor(num)
		var num2 = Math.ceil(num)
		var layer1 = "l" +num1
		var layer2 = "l" +num2
		var raw1 = IKM.crud('selectValue', {
			table: "pdm_job_stack_layers",
			field: ["raw_thk"],
			where: {job_id:JobId, layer_num:num1}
		})
		var raw2 = IKM.crud('selectValue', {
			table: "pdm_job_stack_layers",
			field: ["raw_thk"],
			where: {job_id:JobId, layer_num:num2}
		})
		var raw;
		if(raw1 != raw2) {
			raw = Number(raw1) > Number(raw2) ? raw1 : raw2;
			info[getRow(layer1,layerCount)] = raw
			info[getRow(layer2,layerCount)] = raw
		}
	})
	stepList.forEach(function(step){
		GEN.openStep({job:job, name:step})
		GEN.units({type:par.units})
		GEN.clearLayers()
		GEN.affectedLayer({affected:'no',mode:'all'})
		if(checklist_cfg){
			GEN.affectedLayer({affected:'yes',layer:n_layers})
			Object.keys(checklist_cfg).forEach(function(key){
				if(GEN.getChecklist({job:"genesislib",step:"checklib"}).indexOf(key) > 0){
					var v = checklist_cfg[key]
					if(GEN.isChklistExists({job:job,step:step,chklist:key})){
						GEN.COM("chklist_delete", { chklist: key })
					} 
					GEN.chklistFromLib({chklist:key})
					v.forEach(function(nact){
						GEN.COM('chklist_open,chklist='+key)
						GEN.COM('chklist_show,chklist='+key)
						GEN.chklistRun({chklist:key, nact:nact })
						GEN.chklistResShow({chklist:key,nact:nact})
					})
				}
			})
		}else {
			if(layer_type == "outer"){
				if (  jtg_etch_process_mode== "plat_grapic") { 
						var raw_thk = copper_etching_thk_outer
						var rs = getBc({side: layer_type, paw:raw_thk, jtg_etch_process_mode:jtg_etch_process_mode })

						// 孤立孔
						var tmp_layer = "drl_tmp";
						if(GEN.isLayerExists({job:job, layer:tmp_layer})){GEN.deleteLayer({job:job, layer:tmp_layer})}
						GEN.workLayer({name:'drl',display_number:2,clear_before:'yes'})
						GEN.selectByFilter({attribute:[{attribute:'.drill',option:'via'}]})
						GEN.selectByFilter({attribute:[{attribute:'.drill',option:'plated'}]})
						if(GEN.getSelectCount()>0){
							GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer,invert:'no',dx:0,dy:0,size:900})
							GEN.clearLayers()
							GEN.affectedLayer({affected:'no',mode:'all'})
							GEN.workLayer({name:tmp_layer,display_number:2,clear_before:'yes'})
							GEN.COM('filter_set',{filter_name : 'popup',update_popup : 'no',feat_types : 'pad'});
							n_layers.forEach(function(layer){
								GEN.COM("sel_ref_feat,layers="+layer+",use=filter,mode=disjoint,pads_as=shape,f_types=line\;surface\;arc\;text,polarity=positive\;negative,include_syms=,exclude_syms=")
								// 选中的话就是孤立孔
								if (GEN.getSelectCount()>0) {
									// 张大200拷贝过去 
									GEN.selCopyOther({dest:'layer_name',target_layer:layer,invert:'no',dx:0,dy:0,size:-500})
								}
							})
							GEN.deleteLayer({job:job, layer:tmp_layer})
						}


						
						GEN.affectedLayer({affected:"yes",layer:n_layers,clear_before:"yes"})
						GEN.COM("chklist_single",{action:"valor_dfm_sigopt",show:"yes"});
						GEN.COM("chklist_erf,chklist=valor_dfm_sigopt,nact=1,erf="+erf) 
						GEN.COM("chklist_cupd,chklist=valor_dfm_sigopt,nact=1,params=((pp_layer=.affected)(pp_min_pth_ar="+rs+")(pp_opt_pth_ar="+rs+")(pp_min_via_ar="+rs+")(pp_opt_via_ar="+rs+")(pp_min_microvia_ar=0)(pp_opt_microvia_ar=0)(pp_min_spacing=1)(pp_opt_spacing=1)(pp_min_p2p_spacing=1)(pp_opt_p2p_spacing=1)(pp_min_line=70)(pp_opt_line=70)(pp_nd_percent=25)(pp_abs_min_line=75)(pp_min_pth2c=50)(pp_selected=All)(pp_work_on=Pads)(pp_modification=PadUp)),mode=regular" );
						GEN.COM("chklist_run",{chklist:"valor_dfm_sigopt",nact:1,area:"profile"});
						GEN.COM("chklist_res_show,chklist=valor_dfm_sigopt,nact=1,x=0,y=0,w=0,h=0")

					

				} else  {
					var profile_limits = _.values(GEN.getLayerSymsHist({job:job,step:step,layer:"drl",units:'mm'})) 
					var raw_thk = copper_etching_thk_outer;
					if(raw_thk) {
						var rs = getBc({side: layer_type, paw:raw_thk, jtg_etch_process_mode:jtg_etch_process_mode })
						var tmp = profile_limits.map(function(item){
							if(item.symbol){
								var d = parseFloat(item.symbol.slice(1))
								if(d<2000){
									return { symbol:item.symbol, ditem:rs[0]}
								}else if(d>=2000 && d<3000){
									return {symbol:item.symbol, ditem:rs[1]}
								}else if (d>=3000 && d<4000){
									return { symbol:item.symbol,ditem:rs[2]}
								}else if (d>=4000 && d<5000){
									return { symbol:item.symbol,ditem:rs[3]}
								}else if (d>=5000 && d<=7000){
									return { symbol:item.symbol,ditem:250}
								}
							}
						});
						GEN.affectedLayer({affected:"yes",layer:n_layers,clear_before:"yes"})
						tmp.forEach(function(item){
							var ditem = item.ditem
							if(ditem){
								GEN.COM('filter_set',{filter_name : 'popup',update_popup : 'no',feat_types : 'pad'});
								GEN.COM('filter_set',{filter_name : 'popup',update_popup : 'no',include_syms : item.symbol});
								GEN.selRefFeat({layers:'drl',use:'filter',mode:'include'})
								if(GEN.getSelectCount()>0){
									GEN.COM( "chklist_single",{action:"valor_dfm_sigopt",show:"yes"});
									GEN.COM("chklist_erf,chklist=valor_dfm_sigopt,nact=1,erf="+erf) 
									GEN.COM( "chklist_cupd,chklist=valor_dfm_sigopt,nact=1,params=((pp_layer=.affected)(pp_min_pth_ar="+ditem+")(pp_opt_pth_ar="+ditem+")(pp_min_via_ar="+ditem+")(pp_opt_via_ar="+ditem+")(pp_min_microvia_ar=0)(pp_opt_microvia_ar=0)(pp_min_spacing=1)(pp_opt_spacing=1)(pp_min_p2p_spacing=1)(pp_opt_p2p_spacing=1)(pp_min_line=70)(pp_opt_line=70)(pp_nd_percent=25)(pp_abs_min_line=70)(pp_min_pth2c=50)(pp_selected=Selected)(pp_work_on=Pads\;SMDs\;Drills)(pp_modification=PadUp)),mode=regular" );
									GEN.COM( "chklist_run",{chklist:"valor_dfm_sigopt",nact:1,area:"profile" });
									GEN.COM("chklist_res_show,chklist=valor_dfm_sigopt,nact=1,x=0,y=0,w=0,h=0")
								}
							}
						})
					}
					
				}
				// 获取drl层的
			} else {
				n_layers = n_layers.map(function(v){
					return { layer:v, raw: info[v] }
				})
				var tmp_info = {};
				n_layers.forEach(function(item){
					if(item.raw){
						if(tmp_info[item.raw]){
							tmp_info[item.raw].push(item.layer)
						} else {
							tmp_info[item.raw] = [item.layer]
						}
					}
				})
				for (var raw_thk in tmp_info) {
					var layers = tmp_info[raw_thk];
					var rs = getBc({side: layer_type, paw:raw_thk })
					GEN.affectedLayer({affected:"yes",layer:layers,clear_before:"yes"})
					GEN.COM("chklist_single",{action:"valor_dfm_sigopt",show:"yes"});
					GEN.COM("chklist_erf,chklist=valor_dfm_sigopt,nact=1,erf="+erf);
					GEN.COM("chklist_cupd,chklist=valor_dfm_sigopt,nact=1,params=((pp_layer=.affected)(pp_min_pth_ar="+rs+")(pp_opt_pth_ar="+rs+")(pp_min_via_ar="+rs+")(pp_opt_via_ar="+rs+")(pp_min_microvia_ar=0)(pp_opt_microvia_ar=0)(pp_min_spacing=1)(pp_opt_spacing=1)(pp_min_p2p_spacing=1)(pp_opt_p2p_spacing=1)(pp_min_line=70)(pp_opt_line=70)(pp_nd_percent=25)(pp_abs_min_line=75)(pp_min_pth2c=50)(pp_selected=All)(pp_work_on=Pads)(pp_modification=PadUp)),mode=regular" );
					GEN.COM("chklist_run",{chklist:"valor_dfm_sigopt",nact:1,area:"profile"});
					GEN.COM("chklist_res_show,chklist=valor_dfm_sigopt,nact=1,x=0,y=0,w=0,h=0")
				}
			}
			GEN.affectedLayer({affected:'no',mode:'all'})
		}
	})
    // GEN.deleteLayer({job:job,layer:n_layers.map(function(v){return v + "+++"})})
	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}
	


    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}

function getJobInfo(key){
	return IKM.get_jobinfo({jobid:JobId, jobinfo:key})
}





function getRow( signal1, layerCount) {
    signal1 = Number(signal1.slice(1)) 
    if (signal1 == 1) {
        return "gtl"
    } else if (signal1 == layerCount) {
        return "gbl"
    } else {
        return "l" + signal1
    }
}


function getBc(props) {
    var side = props.side;
    var paw = props.paw;
    var jtg_etch_process_mode = props.jtg_etch_process_mode;
    if (side == "inner") {
        if(paw <= 18) {return isGjb? 125 : 100} 
        else if (paw <=35) {return isGjb? 133:125}
        else if (paw <=70) {return isGjb? 152:133}
        else if (paw <=105) {return isGjb? 178:152}
    } else if (side == "outer") {
        if (  jtg_etch_process_mode== "mask_hole") { //酸蚀
            if(paw <= 50 && paw >= 33) {return [125,150,175,200]} 
            else if (paw <= 70 && paw >= 51) {return [150,175,200,225]}
            else if (paw <= 85 && paw >= 71) {return [175,200,225,250]}
            else if (paw <= 105 && paw >= 86) {return [200,225,250,250]}
            else if (paw <= 130 && paw >= 106) {return [225,250,250,250]}
        } else if(  jtg_etch_process_mode== "plat_grapic") {
            if(paw <= 25 ) {return !isGjb? 75:100}
            else if (paw <= 32 ) {return !isGjb? 90:115}
            else if (paw <= 42 ) {return !isGjb? 105:135}
            else if (paw <= 60 ) {return !isGjb? 130:165}
            else if (paw <= 75 ) {return !isGjb? 145:175}
            else if (paw <= 95 ) {return !isGjb? 165:195}
        }
    } 
    return 0
}